package com.quiz.bis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quiz.bis.domain.model.ExamMonitoringLog;
import com.quiz.bis.mapper.ExamMonitoringLogMapper;
import com.quiz.bis.service.IExamMonitoringService;
import com.quiz.common.core.domain.R;
import com.quiz.common.mybatis.core.page.PageQuery;
import com.quiz.common.utils.DateUtils;
import com.quiz.common.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * 监考记录服务实现
 * @author ahuan
 */
@Service
@RequiredArgsConstructor
public class ExamMonitoringServiceImpl implements IExamMonitoringService {

    private final ExamMonitoringLogMapper monitoringLogMapper;

    @Override
    public R<Long> logMonitoringEvent(ExamMonitoringLog log) {
        log.setEventTime(new Date());
        log.setUserId(SecurityUtils.getUserId());
        monitoringLogMapper.insert(log);
        return R.ok(log.getId());
    }

    @Override
    public R<Boolean> handleMonitoringEvent(Long logId, String handleResult) {
        ExamMonitoringLog log = monitoringLogMapper.selectById(logId);
        if (log == null) {
            return R.fail("监考记录不存在");
        }

        log.setHandleResult(handleResult);
        log.setHandleBy(SecurityUtils.getUserId());
        log.setUpdateTime(new Date());
        monitoringLogMapper.updateById(log);
        return R.ok(true);
    }

    @Override
    public Page<ExamMonitoringLog> selectPage(Long groupId, Long examId, Long sessionId, Long userId, Integer eventType, Integer status, String startTime, String endTime, PageQuery page) {

            LambdaQueryWrapper<ExamMonitoringLog> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(ExamMonitoringLog::getDelFlag, 0)
                    .eq(Objects.nonNull(groupId), ExamMonitoringLog::getGroupId, groupId)
                    .eq(Objects.nonNull(examId), ExamMonitoringLog::getExamId, examId)
                    .eq(Objects.nonNull(sessionId), ExamMonitoringLog::getSessionId, sessionId)
                    .eq(Objects.nonNull(userId), ExamMonitoringLog::getUserId, userId)
                    .eq(Objects.nonNull(eventType), ExamMonitoringLog::getEventType, eventType)
                    .eq(Objects.nonNull(status) && status == 1, ExamMonitoringLog::getHandleBy, 0)
                    .ge(Objects.nonNull(startTime), ExamMonitoringLog::getEventTime, DateUtils.parseDate(startTime))
                    .le(Objects.nonNull(endTime), ExamMonitoringLog::getEventTime, DateUtils.parseDate(endTime))
                    .orderByDesc(ExamMonitoringLog::getEventTime);

            return monitoringLogMapper.selectPage(page.build(), wrapper);
    }
}